<template>
  <div style="height: 100%">
    <a-radio-group
      v-model="orderOrRefund"
      type="button"
      style="margin-bottom: 10px"
      @change="onChange"
    >
      <a-radio :value="1">订单</a-radio>
      <a-radio :value="0">退单</a-radio>
    </a-radio-group>
    <a-table
      v-if="responseResult.columnsTableList.length && orderOrRefund === 1"
      stripe
      :columns="columnsTable"
      :data="responseResult.columnsTableList"
      :expandable="expandableColumnsTable"
      row-key="sn"
      :pagination="paginationParams"
      @page-change="pageChange"
    >
      <template #orderStatus="{ record }"
        ><div>{{ orderClientStatus[record.orderStatus] }}</div></template
      >
      <template #flowPrice="{ record }"
        ><div>{{ unitPrice(record.flowPrice, '￥') }}</div></template
      >
      <template #options="{ record }"
        ><a-button type="text" status="success" @click="orderDetails(record)"
          >查看</a-button
        ></template
      >
    </a-table>
    <a-table
      v-if="responseResult.refundColumnsList.length && orderOrRefund === 0"
      stripe
      :columns="refundColumns"
      :data="responseResult.refundColumnsList"
      :expandable="expandableRefundColumns"
      row-key="sn"
      :pagination="paginationParams"
      @page-change="pageChange"
    >
      <template #goodsImage="{ record }"
        ><a-image width="60" :src="record.goodsImage"></a-image
      ></template>
      <template #serviceType="{ record }"
        ><div>{{ serviceTypeClient[record.serviceType] }}</div></template
      >
      <template #serviceStatus="{ record }"
        ><div>{{ serviceStatusClient[record.serviceStatus] }}</div></template
      >
      <template #applyRefundPrice="{ record }"
        ><div>{{ unitPrice(record.applyRefundPrice, '￥') }}</div></template
      >
      <template #flowPrice="{ record }"
        ><div>{{ unitPrice(record.flowPrice, '￥') }}</div></template
      >
      <template #options="{ record }"
        ><a-button type="text" status="success" @click="refundDetails(record)"
          >查看</a-button
        ></template
      >
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, watch, h, ref } from 'vue';
  import { useUserStore } from '@/store';
  import { PreViewParamsRule } from '@/types/global';
  import {
    statisticsOrderList,
    statisticsOrderRefundList,
  } from '@/api/statisitics';
  import { unitPrice } from '@/utils/filters';
  import {
    orderClientStatus,
    payStatusClient,
    paymentMethodClient,
    serviceTypeClient,
    serviceStatusClient,
    serviceTypeList,
  } from '@/utils/typeEnumeration';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const orderOrRefund = ref(1); // 订单or退单
  const props = defineProps({
    dateType: {
      type: Object,
      default: () => {
        return {
          recent: 'LAST_SEVEN',
          month: '',
        };
      },
    },
  });
  // 分页的属性配置
  const paginationParams = ref();
  // 订单请求参数
  const previewParams = reactive<PreViewParamsRule>({
    searchType: props.dateType.recent, // TODAY ,  YESTERDAY , LAST_SEVEN , LAST_THIRTY
    year: props.dateType.month || new Date().getFullYear(),
    storeId: useUserStore().userInfo.id,
    pageNumber: 1,
    pageSize: 10,
  });
  // 订单统计
  const columnsTable = [
    { title: '商家名称', dataIndex: 'storeName' },
    { title: '用户名', dataIndex: 'memberName' },
    { title: '订单状态', dataIndex: 'orderStatus', slotName: 'orderStatus' },
    { title: '创建时间', dataIndex: 'createTime' },
    { title: '支付时间', dataIndex: 'paymentTime' },
    { title: '价格', dataIndex: 'flowPrice', slotName: 'flowPrice' },
    { title: '操作', slotName: 'options' },
  ];
  // 退单统计
  const refundColumns = [
    { title: '商品图片', dataIndex: 'goodsImage', slotName: 'goodsImage' },
    { title: '商品名称', dataIndex: 'goodsName' },
    { title: '商家名称', dataIndex: 'storeName' },
    { title: '售后单类型', dataIndex: 'serviceType', slotName: 'serviceType' },
    {
      title: '售后单状态',
      dataIndex: 'serviceStatus',
      slotName: 'serviceStatus',
    },
    { title: '退款时间', dataIndex: 'refundTime' },
    {
      title: '申请退款金额',
      dataIndex: 'applyRefundPrice',
      slotName: 'applyRefundPrice',
    },
    { title: '申请原因', dataIndex: 'reason' },
    { title: '实际金额', dataIndex: 'flowPrice', slotName: 'flowPrice' },
    { title: '操作', slotName: 'options' },
  ];
  // 传递的参数
  interface ResponseRule {
    columnsTableList: Array<any>;
    refundColumnsList: Array<any>;
  }
  const responseResult = reactive<ResponseRule>({
    columnsTableList: [],
    refundColumnsList: [],
  });
  // 订单的展开行配置
  const expandableColumnsTable = reactive<any>({
    title: '',
    width: 80,
    slotName: 'extra',
    expandedRowRender: (record: any) => {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      return h(
        'div',
        {
          style: { color: '', border: '' },
          class: 'my-expandable',
          id: '',
        },
        [
          // "render函数文本" 文本内容可以直接写入
          h('div', [
            h('div', { class: 'title' }, '订单详情'),
            h('div', { class: 'order-detail' }, [
              h('p', [h('span', '订单来源'), h('span', record.clientType)]),
              h('p', [
                h('span', '订单状态'),
                h('span', orderClientStatus[record.orderStatus]),
              ]),
              h('p', [
                h('span', '付款状态'),
                h('span', payStatusClient[record.payStatus]),
              ]),
              h('p', [h('span', '支付时间'), h('span', record.paymentTime)]),
              h('p', [
                h('span', '支付方式'),
                h('span', paymentMethodClient[record.paymentMethod]),
              ]),
              h('p', [h('span', '用户名'), h('span', record.memberName)]),
              h('p', [h('span', '店铺名称'), h('span', record.storeName)]),
              h('p', [h('span', '创建时间'), h('span', record.createTime)]),
            ]),
            h('div', { class: 'title' }, '商品详情'),
            record.orderItems.map((item: any) => {
              return h('div', { class: 'goods-detail' }, [
                h('img', { src: item.image }),
                h('div', [
                  h('p', item.name),
                  h('p', `x${item.num}`),
                  h('p', unitPrice(item.goodsPrice, '￥')),
                ]),
              ]);
            }),
            h('div', { class: 'flow-price' }, [
              h('span', '总价格'),
              h('span', unitPrice(record.flowPrice, '￥')),
            ]),
          ]), // h()创建的VNodes
          // h({template: `<div><div>${record.orderItems[0].sn}</div></div>`})
        ]
      );
      // return (JSON.stringify(record.orderItems))
    },
  });
  // 退单的展开行配置
  const expandableRefundColumns = reactive({
    title: '',
    width: 80,
    slotName: 'extra',
    expandedRowRender: (record: any) => {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      return h(
        'div',
        {
          style: { color: '', border: '' },
          class: 'my-expandable',
          id: '',
        },
        [
          // "render函数文本" 文本内容可以直接写入
          h('div', [
            h('div', { class: 'title' }, '售后详情'),
            h('div', { class: 'order-detail' }, [
              h('p', [
                h('span', '售后类型'),
                h('span', serviceTypeList[record.serviceType]),
              ]),
              h('p', [
                h('span', '售后单状态'),
                h('span', serviceStatusClient[record.serviceStatus]),
              ]),
              h('p', [h('span', '退款时间'), h('span', record.refundTime)]),
              h('p', [
                h('span', '申请退款金额'),
                h('span', unitPrice(record.applyRefundPrice, '￥')),
              ]),
              h('p', [h('span', '商家备注'), h('span', record.auditRemark)]),
              h('p', [h('span', '申请原因'), h('span', record.reason)]),
              h('p', [h('span', '用户名'), h('span', record.memberName)]),
              h('p', [h('span', '店铺名称'), h('span', record.storeName)]),
              h('p', [h('span', '创建时间'), h('span', record.createTime)]),
            ]),
            h('div', { class: 'title' }, '商品详情'),
            h('div', { class: 'goods-detail' }, [
              h('img', { src: record.goodsImage }),
              h('div', [
                h('p', record.name),
                h('p', `x${record.num}`),
                h('p', unitPrice(record.goodsPrice, '￥')),
              ]),
            ]),
            h('div', { class: 'flow-price' }, [
              h('span', '实际退款金额'),
              h('span', unitPrice(record.flowPrice, '￥')),
            ]),
          ]), // h()创建的VNodes
          // h({template: `<div><div>${record.orderItems[0].sn}</div></div>`})
        ]
      );
    },
  });
  // 订单跳转详情页
  const orderDetails = (record: any) => {
    router.push({
      name: 'order-detail',
      query: { id: record.sn },
    });
  };
  // 退单跳转详情页
  const refundDetails = (record: any) => {
    router.push({
      name: 'return-goods-detail',
      query: { id: record.sn },
    });
  };
  // 统计相关--订单统计
  const getOrderList = async () => {
    const res = await statisticsOrderList(previewParams);
    if (res.data && res.data.success) {
      responseResult.columnsTableList = res.data.result.records;
      paginationParams.value = res.data.result;
    }
  };
  // 统计相关--退单统计
  const getOrderRefundList = async () => {
    const res = await statisticsOrderRefundList(previewParams);
    if (res.data.success) {
      responseResult.refundColumnsList = res.data.result.records;
      paginationParams.value = res.data.result;
    }
  };
  // 表格分页
  const pageChange = (number: number) => {
    previewParams.pageNumber = number;
    if (orderOrRefund.value == 1) {
      getOrderList();
    } else {
      getOrderRefundList();
    }
  };
  // 订单/退单切换
  const onChange = () => {
    previewParams.pageNumber = 1;
    if (orderOrRefund.value == 1) {
      getOrderList();
    } else {
      getOrderRefundList();
    }
  };
  onMounted(() => {
    getOrderList();
  });
  // 监听值的改变 父级值改变
  watch(
    () => props.dateType,
    (val) => {
      previewParams.searchType = val.recent;
      if (val.month) {
        // eslint-disable-next-line prefer-destructuring,no-nested-ternary
        previewParams.month = val.month.split('-')[1]
          ? val.month.split('-')[1].indexOf('0') != -1
            ? val.month.split('-')[1].substr(1)
            : ''
          : '';
        // eslint-disable-next-line prefer-destructuring
        previewParams.year = val.month.split('-')[0];
      }
      getOrderList();
      getOrderRefundList();
    },
    {
      deep: true,
      immediate: true,
    }
  );
</script>

<style scoped lang="less">
  :deep(.my-expandable) {
    .title {
      font-size: 18px;
      line-height: 50px;
      font-weight: bold;
    }
    .order-detail {
      display: flex;
      flex-wrap: wrap;
      p {
        width: 300px;
        height: 40px;
        line-height: 40px;
        margin: 0;
        color: #666666;
        span:nth-of-type(1) {
          margin-right: 16px;
          font-weight: bold;
        }
      }
    }
    .goods-detail {
      display: flex;
      margin-bottom: 20px;
      img {
        width: 100px;
        height: 100px;
        border-radius: 10px;
      }
      > div {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 18px;
        p {
          margin: 0;
          line-height: 24px;
        }
        p:nth-of-type(3) {
          color: #ff0000;
          font-weight: bold;
        }
      }
    }
    .flow-price {
      text-align: right;
      padding-right: 20%;
      font-size: 16px;
      span:nth-of-type(1) {
        margin-right: 18px;
      }
      span:nth-of-type(2) {
        color: #ff0000;
        font-size: 24px;
        font-weight: bold;
      }
    }
  }
</style>
